<template>
  <!-- 搜索区域 -->
  <div class="main-content">

    <IsLoading v-if="isLoading"></IsLoading>

    <div class="scalable-container" :style="{ transform: `scale(${scale})`, transformOrigin: 'top' }">
      <!-- 页面内容 -->
      <div class="content">

        <!-- 面包屑和搜索结果计数 -->
        <div style="display: flex; flex-direction: column;">
          <!-- 面包屑 -->
          <el-breadcrumb separator-class="el-icon-arrow-right" class="custom-breadcrumb">
            <el-breadcrumb-item :to="{ path: '/front/homeFront' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: $route.path }">{{ $route.meta.name }}</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 搜索结果计数 -->
          <span class="custom-span"><b style="font-size: 20px">{{ name }} </b>  一共<b
              style="font-size: 20px">{{ total }}</b>个结果</span>
        </div>

        <!-- 搜索结果列表 -->
        <div @click="toDetail(item.id, item.categoryId)" v-for="(item, i) in searchLists" :key="i"
             class="card" v-if="number">
          <img :src="IMAGE_URL + item.img" class="img">
          <div style="display: flex;flex: 1;flex-direction: column;">
            <!--        第一行区域-->
            <div style="display: flex;flex: 1">
              <div class="name">{{ item.name }}</div>
              <!--              <div class="slugName">（{{ item.slugName }}）</div>-->
              <div class="time">发布时间：{{ item.createTime }}</div>
              <div class="time">更新时间：
                <span v-if="item.updateTime">{{ item.updateTime }}</span>
                <span v-else>暂无</span>
              </div>
            </div>
            <!--      第二行区域-->
            <div style="margin: 8px 0">
              介绍：<span v-if="item.introduction">{{ item.introduction }}</span>
              <span v-else>暂无</span>
            </div>
          </div>
          <el-button plain type="primary"
                     style="width: 10%;height: 5%;margin: 30px 20px">前往查看
          </el-button>
        </div>
        <div v-if="!number" class="empty">
          <img src="@/assets/imgs/noNumber.png" style="display: flex;align-items: center"/>
        </div>

        <!-- 分页区域 -->
        <div class="pagination" style="display: flex; justify-content: flex-end; margin: 25px 0;">
          <el-pagination background @current-change="handleCurrentChange" :current-page.sync="pageNum"
                         :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
                         @size-change="handleSizeChange" :page-size="pageSize"
                         layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        </div>
        <!--        </el-scrollbar>-->

        <!-- 遮罩层 -->
        <!--        <div v-if="isDelete" class="overlay"></div>-->

        <!--        <div class="tip" v-if="isDelete">-->
        <!--          <h1 class="tip-title">提示</h1>-->
        <!--          <p class="delete">确定要删除历史记录吗？</p>-->
        <!--          <el-button class="button" type="text" @click="isDelete = false"-->
        <!--                     style="color: rgb(0, 0, 0); font-size: 16px;border-right: 1px solid #e0e0e0;padding-right: 18%">-->
        <!--            取消-->
        <!--          </el-button>-->
        <!--          <el-button class="button" type="text" @click="cleanHistory"-->
        <!--                     style="color: rgb(0, 122, 255); font-size: 16px;padding-left: 18%">-->
        <!--            确定-->
        <!--          </el-button>-->
        <!--        </div>-->

      </div>
    </div>
  </div>
</template>

<script>
import config from "../../../config";

export default {
  name: "Search",
  data() {
    return {
      IMAGE_URL: config.IMAGE_URL,
      searchLists: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      id: '',
      scale: 1,  // 初始缩放比例为 1，即原始大小
      pid: '',
      buttonItems: [],
      // 搜索关键词的历史记录
      historyList: JSON.parse(localStorage.getItem('name') || '[]'),
      name: '',
      wh: 0,
      whpc: 0,
      isDelete: false,
      isLoading: true,
      number: true,
    };
  },
  // computed: {
  //   historys() {
  //     return [...this.historyList].reverse()
  //   }
  // },
  // created() {
  //   this.updateFormFromQuery();
  //
  //   this.fetchData()
  //   this.load()
  // },
  created() {
    this.updateFormFromQuery()
    Promise.all([
      this.fetchData(),
      this.load()
    ]).then(() => {
      this.isLoading = false;
    }).catch((error) => {
      console.error('Error loading data:', error);
      this.isLoading = false;
    });
  },
  mounted() {
    // 监听滚轮事件
    window.addEventListener('wheel', this.handleWheelEvent);
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('wheel', this.handleWheelEvent);
  },
  watch: {
    '$route.query.name': function (newName) {
      this.name = newName || '';
      this.fetchData()
      this.load()
    },

    '$route.query.nameId': function (newNameId) {
      this.nameId = newNameId || '';
      this.fetchData()
      this.load()
    }
  },
  methods: {
    updateFormFromQuery() {
      this.name = this.$route.query.name || '';
      this.nameId = this.$route.query.nameId || '';
      if (this.nameId === '分类')
        this.nameId = 1
    },
    //查询左边按钮数据
    load() {
      return this.$request.get('/apis/downCategories/list', {
        params: {
          type: 1,
          typeId: this.nameId
        }
      }).then(res => {
        this.buttonItems = res.data.sort((a, b) => a.showOrder > b.showOrder ? 1 : -1)
      })
    },
    handleWheelEvent(event) {
      // 检查是否按下了Ctrl键
      if (event.ctrlKey) {
        // 防止页面的默认缩放行为
        //event.preventDefault();

        // 判断滚轮方向
        if (event.deltaY < 0) {
          // 滚轮向上滚动，放大页面
          this.scale = Math.min(this.scale + 0.1, 2);  // 最大放大到2倍
        } else {
          // 滚轮向下滚动，缩小页面
          this.scale = Math.max(this.scale - 0.1, 0.5);  // 最小缩小到0.5倍
        }
      }
    },
    //每个软件的详情区域
    toDetail(id, categoryId) {
      this.$request.get(`/apis/downCategories/${categoryId}`, {
        params: {
          typeId: this.nameId
        }
      }).then(res => {
        this.pid = res.data.pid;

        const item = this.buttonItems.find(item => item.id === this.pid);
        const categoryName = item ? item.name : '未找到对应的名称';

        if (this.nameId === 1) {
          this.$router.push({
            name: 'HomeDetail',
            query: {
              id: id,
              categoryName: categoryName
            }
          })
        } else if (this.nameId === 2) {
          this.$router.push({
            name: 'FaceDetail',
            query: {
              id: id,
              categoryName: categoryName
            }
          })
        } else {
          this.$router.push({
            name: 'DriveDetail',
            query: {
              id: id,
              categoryName: categoryName
            }
          })
        }

      })
    },
    fetchData() {
      this.number = true
      this.isLoading = true
      return this.$request.get(`/apis/downResources/${this.pageNum}/${this.pageSize}`, {
        params: {
          search: this.name,
          typeId: this.nameId
        }
      }).then(res => {
        this.searchLists = res.data?.list
        this.total = res.data?.total
        this.isLoading = false
        if (this.total === 0) {
          // this.$router.push({
          //   name: 'Empty',
          //   historyList: this.historyList
          // })
          this.number = false
        }
        // this.saveSearchHistory()
      })
    },
    goDetail(name) {
      this.name = name
      this.fetchData()
    },
    // 保存搜索关键词为历史记录
    saveSearchHistory() {
      const set = new Set(this.historyList)
      set.delete(this.name)
      set.add(this.name)
      this.historyList = Array.from(set)
      localStorage.setItem('name', JSON.stringify(this.historyList))
    },
    // 清空搜索历史记录
    cleanHistory() {
      this.historyList = [];
      localStorage.setItem('name', JSON.stringify([]));
      this.isDelete = false;
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.fetchData(); // 更新页码后重新请求数据
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.fetchData(); // 更新每页条数后重新请求数据
    },
  },
};
</script>

<style scoped>
.custom-breadcrumb {
  /* 调整垂直位置，使面包屑稍微靠下 */
  margin-top: 20px;
  /* 调整水平位置，使面包屑距离左边有一定距离 */
  padding-left: 20px; /* 或者使用 margin-left */
  justify-content: flex-start;
}

.custom-span {
  margin: 20px 0;
  padding-left: 20px;
  font-size: 17px;
}

.card {
  display: flex;
  flex-direction: row;
  margin: 10px;
  padding: 20px;
  background: white;
}

.img {
  width: 85px;
  height: 85px;
  margin-right: 20px;
}

.name {
  font-size: 20px;
  margin: 7px 0;
  font-weight: bold;
}

.slugName {
  font-size: 15px;
  margin: 7px 0;
}

.time {
  font-size: 15px;
  margin: 7px 8px;
}

.main-content {
  width: 1200px; /* 设置最大宽度 */
  margin: 0 auto; /* 居中显示 */
}

.empty {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;
  height: 100vh;
}
</style>